package com.xtayfjpk.security;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;

import org.junit.Test;

public class KeyPairTest {
	private static final String ALGOGRITHM = "RSA";
	private static final String PUBLIC_KEY_PATH = "public.key";
	private static final String PRIVATE_KEY_PATH = "private.key";
	
	@Test
	public void testGenerate() throws Exception {
		KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGOGRITHM);
		KeyPair keyPair = generator.generateKeyPair();
		PublicKey publicKey = keyPair.getPublic();
		PrivateKey privateKey = keyPair.getPrivate();
		
		writeKey(PUBLIC_KEY_PATH, publicKey);
		writeKey(PRIVATE_KEY_PATH, privateKey);
	}
	
	@Test
	public void testEncryptAndDecrypt() throws Exception {
		Cipher cipher = Cipher.getInstance(ALGOGRITHM);
		PrivateKey privateKey = (PrivateKey) readKey(PRIVATE_KEY_PATH);
		cipher.init(Cipher.ENCRYPT_MODE, privateKey);
		//加密
		String sendInfo = "我的明文";
		byte[] results = cipher.doFinal(sendInfo.getBytes());
		
		
		PublicKey publicKey = (PublicKey) readKey(PUBLIC_KEY_PATH);
		cipher.init(Cipher.DECRYPT_MODE, publicKey);
		byte[] deciphered = cipher.doFinal(results);
		String recvInfo = new String(deciphered);
		System.out.println(recvInfo);
	}
	
	public void writeKey(String path, Key key) throws Exception {
		FileOutputStream fos = new FileOutputStream(path);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(key);
		oos.close();
	}
	
	public Key readKey(String path) throws Exception {
		FileInputStream fis = new FileInputStream(path);
		ObjectInputStream bis = new ObjectInputStream(fis);
		Object object = bis.readObject();
		bis.close();
		return (Key) object;
	}
}
